package com.educate.ucenter.rpc.provide.config;


import com.educate.common.utils.exception.AppException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

@Data
@Component
@ConfigurationProperties(prefix = "educate.ucenter.wx")
public class WxConfig {

    private String appId;

    private String appSecret;

    public String getLoginUrl(String wxLoginCode) {
        return String.format("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code",
                getAppId(), getAppSecret(), wxLoginCode);
    }

    public static String wxUserDecode(String encryptedData, String aesKey, String iv) {
        try {
            byte[] encryptedBytes = Base64Utils.decode(encryptedData.getBytes());
            byte[] aesKeyBytes = Base64Utils.decode(aesKey.getBytes("ASCII"));
            byte[] ivBytes = Base64Utils.decode(iv.getBytes());
            SecretKeySpec secretKeySpec = new SecretKeySpec(aesKeyBytes, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); // 算法/模式/补码方式
            IvParameterSpec ivParameterSpec = new IvParameterSpec(ivBytes); // 使用CBC模式，需要一个向量iv，可增加加密算法的强度
            cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
            byte[] decryptBytes = cipher.doFinal(encryptedBytes);
            return new String(decryptBytes);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AppException("aes密码失败：" + encryptedData, e);
        }

    }
}
